/*
 * HublistBufferReader.java
 *
 * Created on 17 November 2006, 18:26
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package libjdc.dc.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author root
 */
public class HublistBufferReader extends BufferedReader {
    private static final String HUB_END = "/>";
    private static final String HUB_START = "<Hub ";
    
    public HublistBufferReader(InputStreamReader in) {
        super(in);
    }
    
    private void estadoDescartar() throws IOException{
        int ch;
        while((ch = read()) != -1){
            if(ch == HUB_START.charAt(0)){
                if(estadoHubStart())
                    return;
            }
            //System.out.print((char)ch);
        }
        throw new IOException("Stream is Closed");
        
    }
    
    private boolean estadoHubStart() throws IOException{
        for(int idx = 1 ; idx < HUB_START.length() ; idx++){
            if(read() != HUB_START.charAt(idx)){
                return false;
            }
        }
        return true;
    }
   
    public String readHubLine() throws IOException{
        StringBuffer buffer = new StringBuffer(HUB_START);
        int ch;
        try {
            estadoDescartar();
        } catch (IOException e){
            //e.printStackTrace();
            return null;
        }
        while (!buffer.toString().endsWith(HUB_END))
            if(((ch = read()) == -1))
                throw new IOException("Stream is Closed");
            else
                buffer.append( (char)ch );
        return buffer.toString();
    }
    
   /* public String readLine() throws IOException{
         StringBuffer buffer = new StringBuffer(HUB_START);
         int ch;
         while (!buffer.toString().endsWith(HUB_END))
            if(((ch = read()) == -1))
                throw new IOException("Stream is Closed");
            else
                buffer.append( (char)ch );
        return buffer.toString();
    }
    */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        
        String filename = "/home/dbotelho/PublicHubList.xml";
        HublistBufferReader in = new HublistBufferReader(new InputStreamReader(new FileInputStream(new File(filename))));
        String line;
        while((line = in.readHubLine())!= null){
            System.out.println(line);
        }
    }
}
